package com.ym.excel.jfree;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.plot.DefaultDrawingSupplier;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: smuswc
 * @Date: 2018/2/7 14:04
 * @Description:
 */
public abstract class YMBaseChart implements YMChart {

    public static String fileSeparator = System.getProperty("file.separator");

    // 初始化主题
    static {
        java.awt.Font font = new java.awt.Font("黑体", java.awt.Font.PLAIN, 14);
        // 设置主题中文样式
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
        chartTheme.setExtraLargeFont(font);
        chartTheme.setRegularFont(font);
        chartTheme.setSmallFont(font);
        chartTheme.setSmallFont(font);

        DefaultDrawingSupplier defaultDrawingSupplier = new DefaultDrawingSupplier();
        chartTheme.setDrawingSupplier(defaultDrawingSupplier);
        ChartFactory.setChartTheme(chartTheme);
    }

    public String drawChart(JFreeChart jFreeChart, String path) throws Exception {
        return drawChart(jFreeChart, path, null, null);
    }

    /**
     * 生成生成图片名称
     * @param path
     * @return
     */
    public String getImagePath(String path) {
        String fileName = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        path += fileSeparator + fileName + ".png";
        return path;
    }

    /**
     * 生成图片公共方法
     * @param jFreeChart
     * @param path
     * @param with
     * @param height
     */
    public void generateImage(JFreeChart jFreeChart, String path, Integer with, Integer height) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ChartUtils.writeChartAsJPEG(bos, 1, jFreeChart, with == null ? 520 : with, height == null ? 455 : height);

        FileOutputStream fileOutputStream = new FileOutputStream(path);
        fileOutputStream.write(bos.toByteArray());
        fileOutputStream.flush();
        fileOutputStream.close();
        bos.close();
    }
}
